<template>
  <div>
    <div class="header-search">
          <van-search :clearable="false" v-model="value" placeholder="请输入房产关键词" @input="serach" />
        </div>
        <div class="search-content" v-if="contentList.length>0">
          <p v-for="item in contentList" :key="item" @click="toHouseDetail(item)" v-html="hightligth(item)"></p>
          <p @click="clear">清空搜索记录</p>
        </div>
        <p v-if="flag" class="search-content">暂无该搜索结果</p>
  </div>
</template>

<script>
import { houseList } from '@/api/house'
export default {
  name: 'HouseIndex',

  data () {
    return {
      contentList: [],
      value: '',
      flag: false
    }
  },

  mounted () {

  },

  methods: {
    async serach (value) {
      this.flag = false
      if (value === '') {
        return
      }
      // console.log(value)
      try {
        const res = await houseList({
          _limit: 10,
          title_contains: value
        })
        const arr = []
        res.forEach(item => {
          arr.push(item.title)
        })
        this.contentList = [...new Set(arr)]
        if (this.contentList.length === 0) {
          this.flag = true
        }
        console.log(this.contentList)
      } catch (error) {
        console.log(error)
      }
    },
    clear () {
      this.contentList = []
    },
    async toHouseDetail (title) {
      try {
        const res = await houseList({
          title_contains: title
        })
        // console.log(res)
        const houseId = res[0].id
        this.$router.push(`houseDetail/${houseId}`)
      } catch (error) {
        console.log(error)
      }
    },
    hightligth (text) {
      // text为搜索结果的文本值,this.value为迷糊查询的值
      const hightligthStr = `<span style="color: red">${this.value}</span>`
      const reg = new RegExp(this.value, 'gi')
      return text.replace(reg, hightligthStr)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .header-search{
  display: flex;
  .van-search{
    width:83%;
  }
}
    .search-content{
    margin-left: 27px;
  }
</style>
